package com.exam.controller;


import com.exam.entity.User;
import com.exam.service.UserService;
import com.exam.utils.CookieUtils;
import com.exam.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenzhuo
 * @since 2023-02-04 05:24:05
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @RequestMapping("/register")
    public String register(String username ,String password,String secondPassword){
        try {
            userService.getUserInfo(username,password,secondPassword);
        }catch (RuntimeException exception){
            exception.printStackTrace();  //打印异常栈
            return exception.getMessage();  //返回异常信息
        }

        return "ok";
    }
    @RequestMapping("/login")
    public String login(String username , String password, HttpServletResponse response){
        try{
            User userLoginInfo = userService.getUserLoginInfo(username, password);
            String account = userLoginInfo.getUsername();
            String token = JwtUtils.createToken(account,30);
            CookieUtils.setUserToken2Cookie(response,token);
        }catch (RuntimeException e){
            e.printStackTrace();
            return e.getMessage();
        }

        return "ok";
    }

    @RequestMapping("currentAccount")
    @ResponseBody
    public String getUserName(HttpServletRequest request){
        String account = CookieUtils.getUserTokenFromCookie(request);
        String accountFromToken = JwtUtils.getAccountWithoutException(account);
        return accountFromToken;

    }

    @RequestMapping("loginOut")
    public String loginOut(HttpServletResponse response){
        CookieUtils.deleteUserTokenFromCookie(response);
        return "ok";
    }
}

